package pl.uz.zgora.plan;

import java.io.IOException;
import java.util.ArrayList;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class PersDataSource {
	private SQLiteDatabase database;
	private PersDatabaseHandler dbHelper;
	private NauczycielPersDataSource nauczycielDataSource;
	
	public PersDataSource(Context context, boolean doRemove) {
		dbHelper = new PersDatabaseHandler(context, doRemove);
	}
	
	public PersDataSource(Context context, boolean doRemove, boolean doRecreate) {
		dbHelper = new PersDatabaseHandler(context, doRemove);
	}
	
	public PersDataSource(Context context) throws IOException
	{
		dbHelper = new PersDatabaseHandler(context);
	}
	
	public void openForWrite() throws SQLException
	{
		database = dbHelper.getWritableDatabase();
	}
	
	public void openForRead() throws SQLException, IOException
	{
		dbHelper.createDataBase();
		database =  dbHelper.openDataBase();
	} 
	
	public void writeNauczycielePers(final ArrayList<Nauczyciel> nauczyciele) {
		openForWrite();
		nauczycielDataSource = new NauczycielPersDataSource(database);
		nauczycielDataSource.addNauczycielList(nauczyciele);
		close();
	}
	
	public Integer getTeacherID(String imie, String nazwisko) throws SQLException, IOException {
		openForRead();
		nauczycielDataSource = new NauczycielPersDataSource(database);
		ArrayList<Nauczyciel> nauczyciele = nauczycielDataSource.getNauczyciel(nazwisko);
		
		char[] a = (nazwisko + "  " + imie + " ").toCharArray();
		
		for(Nauczyciel n: nauczyciele) {
			char[] b = n.getNazwa().toCharArray();
			
			if(equals(a, b)) {
				close();
				return n.getIdNauczyciela();
			}
			
			
		}
		close();
		return -1;
	}
	
	private boolean equals(char[] lhs, char[] rhs) {
		if(lhs.length != rhs.length) { return false; }

		for(int i = 0; i < lhs.length; i++) {
			if(lhs[i] == 160) { 
				lhs[i] = 32; 
			}
			if(rhs[i] == 160) { 
				rhs[i] = 32; 
			}
		}

		for(int i = 0; i < lhs.length; i++) {
			if(lhs[i] != rhs[i]) {
				return false;
			}
		}
		
		return true;
	}
	
	public void close()
	{
		dbHelper.close();
	}
}
